//
//  BottomCollectCell1.m
//  Zaker
//
//  Created by lirui on 16/3/9.
//  Copyright © 2016年 dllo. All rights reserved.
//

#import "SeeBottomCollectCell1.h"
#import "SeeVideoCell.h"
#import <UIImageView+WebCache.h>
#import <MediaPlayer/MediaPlayer.h>
#import <View+MASAdditions.h>
#import "KindCell.h"
#import "CoreDataManager.h"
#import "Video.h"
#import "AppDelegate.h"
#import "PlayerManager.h"
#import "SeeRadioViewController.h"
@interface SeeBottomCollectCell1 ()<UITableViewDelegate,UITableViewDataSource,playDelegate,UICollectionViewDataSource,UICollectionViewDelegate>
@property (nonatomic, retain)MPMoviePlayerViewController *movieView;
@property (nonatomic, retain)NSIndexPath *indexpath;//点击的cell的位置
@property (nonatomic, retain)UIButton *button;
@property (nonatomic, assign)BOOL isfull;
@property(nonatomic ,strong)UICollectionView *collection;
@property(nonatomic, strong)NSMutableArray *kindArr;
@property(nonatomic, assign)BOOL isrefresh;
@property(nonatomic, assign)NSInteger i;
@property(nonatomic, strong) CoreDataManager *manager;
@property(nonatomic ,retain)NSMutableArray *arr;
@property(nonatomic ,assign)BOOL collect;
@property(nonatomic,retain)AppDelegate *delegate;

@end

@implementation SeeBottomCollectCell1

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        self.listArr = [ NSMutableArray array];
        [self dataHandler];
        [self creatTableView];
        [self top];
        
        self.manager =  [CoreDataManager defaults];

       
    }
    
    return  self;
}

-(void)dataHandler
{
        NSString *str = [NSString stringWithFormat:@"http://c.m.163.com/nc/video/home/%ld-10.html",_i];
    [LHAFNetworkTool  getUrl:str body:nil response:LHJSON requestHeadFile:nil success:^(NSURLSessionDataTask *task, id resposeObject) {
        
        if (_isrefresh) {
            
            [self.listArr removeAllObjects];
            
        }
        
        

        NSArray *arr = resposeObject[@"videoList"];
        NSArray *arr1 = resposeObject[@"videoSidList"];
        self.kindArr =[SeeModel modelHandlerWithArray:arr1];
       
        [self.listArr addObjectsFromArray:[SeeModel modelHandlerWithArray:arr]];
       [_collection reloadData];
        [_tableView reloadData];
        [self.tableView.mj_header endRefreshing];
        [self.tableView.mj_footer endRefreshing];
        
        
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        
    }];
    
}
-(void)top
{
    //头部的collection
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc]init];
    layout.minimumInteritemSpacing = 0;
    layout.minimumLineSpacing = 0;
    layout.itemSize = CGSizeMake((self.frame.size.width - 4) / 4, (self.frame.size.height - 64) / 6 );
    self.collection = [[UICollectionView alloc]initWithFrame:CGRectMake(0, 0, self.frame.size.width, (self.frame.size.height - 64) / 6) collectionViewLayout:layout];
    [_collection registerClass:[KindCell class] forCellWithReuseIdentifier:@"kindcell"];
    _collection.dataSource = self;
    _collection.delegate = self;
    _collection.backgroundColor =  [UIColor whiteColor];
    self.tableView.tableHeaderView = _collection;
    
    
}
-(void)creatTableView
{
    self.tableView = [[ UITableView alloc] initWithFrame:CGRectMake(0, 0, WIDTH * 375, HEIGHT * 667) style:UITableViewStylePlain];
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    self.tableView.backgroundColor = [UIColor clearColor];
    [self addSubview:self.tableView];
    
    [self.tableView registerClass:[SeeVideoCell class] forCellReuseIdentifier:@"cell"];
    
    [self notificationVideo];
    
    MJRefreshGifHeader *header = [MJRefreshGifHeader headerWithRefreshingBlock:^{
        //赋初值
        _i = 10;
        self.isrefresh = YES;
        
        [self  dataHandler];
    }];
    self.tableView.mj_header = header;
    
    MJRefreshAutoNormalFooter *footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        _i += 10;
        
    self.isrefresh = NO;
        [self dataHandler];
    }];
    self.tableView.mj_footer = footer;
    /**shoucang*/
  
   
       //NSLog(@"url == %@" , [self.manager applicationDocumentsDirectory]);
    


    
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.listArr.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    SeeVideoCell *cell = [ tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
    SeeModel *m = self.listArr[indexPath.row];
    cell.titleLable.text = m.title ;
    cell.detailLable.text = m.description1;
    [cell.myImageView sd_setImageWithURL:[NSURL URLWithString:m.cover]];
    cell.playLable.text = m.playCount.stringValue;
    cell.timeLable.text  = m.length.stringValue;
    cell.delegate = self;
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    UITapGestureRecognizer *tap = [[ UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapAction:)];
    [cell.myImageView addGestureRecognizer:tap];
    cell.myImageView.userInteractionEnabled = YES;
    [cell.share addTarget:self action:@selector(shareAction:) forControlEvents:UIControlEventTouchUpInside];
    
    cell.share.tag = indexPath.row;
    [cell.likeBtn addTarget:self action:@selector(likeAction:) forControlEvents:UIControlEventTouchUpInside];
    cell.likeBtn.tag = indexPath.row;
    _collect = NO;
    cell.likeBtn.selected = NO;
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(change:) name:@"changeLike" object:nil];
    return cell;
    
}
-(void)change:(UIButton *)btn
{
    [_tableView reloadData];
}
-(void)likeAction:(UIButton *)like
{
    
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"Video" inManagedObjectContext:self.manager.managedObjectContext];
    NSFetchRequest *request = [[NSFetchRequest alloc] initWithEntityName:@"Video"];
    NSError *error;
    NSArray *arr = [self.manager.managedObjectContext executeFetchRequest:request error:&error];
       SeeModel  *model = _listArr[like.tag];
    _collect = !_collect;

    if (_collect) {
        //设置收藏属性
        like.selected = YES;
        for (Video *m in arr) {
            if ([m.title isEqualToString:model.title]) {
                return;
            }
        }
        Video *top = [[Video alloc] initWithEntity:entity insertIntoManagedObjectContext:self.manager.managedObjectContext];
        top.title = model.title;
        top.url = model.mp4_url;
        top.detail = model.description1;
        top.vid = model.vid;
        [self.manager saveContext];
    } else {
        like.selected = NO;
        for (Video *m in arr) {
            if ([m.title isEqualToString:model.title]) {
                [self.manager.managedObjectContext deleteObject:m];
            }
        }
        [self.manager saveContext];
    }
    //NSLog(@"数据库收藏:%@", arr);
    NSLog(@"url === %@", [self.manager applicationDocumentsDirectory]);
    
    
}



-(void)shareAction:(UIButton *)btn
{     NSLog(@"%ld",btn.tag);
    [self.sdelegate shareWithurl:[_listArr[btn.tag] mp4_url]];
    
    
}
#pragma mark -tableview的必须协议方法
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
     return self.frame.size.height / 2  ;

}


#pragma mark -collectionview的必须协议方法
//创建collection个数
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return _kindArr.count;
}

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{ KindCell  *cell =[ collectionView dequeueReusableCellWithReuseIdentifier:@"kindcell" forIndexPath:indexPath];
    SeeModel *k = _kindArr[indexPath.item];
    [cell.picture sd_setImageWithURL:[NSURL URLWithString:k.imgsrc]] ;
    cell.title.text = k.title;
    return cell;

    
}
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    self.pushBlock([_kindArr[indexPath.item] sid]);
}
#pragma mark -代理协议方法
-(void)playMovie:(UITapGestureRecognizer *)p
{
       [self moviePlayer:p];
    
}
#pragma mark -手势方法
-(void)tapAction:(UITapGestureRecognizer *)tap
{

   
    
    [self moviePlayer:tap];
}
#pragma mark -创建视频播放器
-(void)moviePlayer:(UITapGestureRecognizer *)tap
    
{if (self.movieView.view) {
        [self.movieView.view removeFromSuperview];
    }
    //点击的哪个ImageView
    UIView *view = tap.view;
    //imageView->contentView->cell
    UITableViewCell *cell = (UITableViewCell *)view.superview.superview;
    self.indexpath = [self.tableView indexPathForCell:cell];//获取被点击的cell的indexPath
    SeeModel *model = _listArr[_indexpath.row];
    self.movieView = [[MPMoviePlayerViewController alloc]initWithContentURL:[NSURL URLWithString:model.mp4_url]];
    self.movieView.view.frame = CGRectMake(10, 60, [UIScreen mainScreen].bounds.size.width - 20, [UIScreen mainScreen].bounds.size.height / 3 + 8);
    [self.movieView.moviePlayer setControlStyle:(MPMovieControlStyleEmbedded)];
    [self.movieView.moviePlayer setControlStyle:(MPMovieControlStyleEmbedded)];
    [cell addSubview:self.movieView.view];
    
    //添加视频关闭按钮
    self.button = [UIButton buttonWithType:UIButtonTypeSystem];
    [self.button addTarget:self action:@selector(close:) forControlEvents:UIControlEventTouchUpInside];
    [self.button setBackgroundImage:[UIImage imageNamed:@"iconfont-cha"] forState:UIControlStateNormal];
    [self.movieView.view addSubview:self.button];
    //设置按钮的相对坐标
    [self.button mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(self.movieView.view).with.offset(-5);
        make.top.equalTo(self.movieView.view.mas_top).with.offset(5);
        make.width.mas_equalTo(20);
        make.height.mas_equalTo(20);
    }];
    
    }
#pragma mark -关闭
- (void)close:(UIButton *)button {
        [self.movieView.moviePlayer stop];
        [self.movieView.moviePlayer pause];
        [self.movieView.view removeFromSuperview];
    }

#pragma mark -通知中心监听视频
-(void)notificationVideo
{
    //视频监听
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(jumpFullScreen) name:@"MPMoviePlayerWillEnterFullscreenNotification" object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(exitFullScreen) name:@"MPMoviePlayerWillExitFullscreenNotification" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(removecell) name:@"remove" object:nil];
    

}
//通知中心 让视频停掉
-(void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    [[NSNotificationCenter defaultCenter]postNotificationName:@"remove" object:nil];
}
-(void)removecell
{
    if (self.movieView.view) {
        //        self.movieView.moviePlayer.pause;
        [self.movieView.view removeFromSuperview];
    }
}
- (void)jumpFullScreen {
    
    self.isfull = YES;
    
}

- (void)exitFullScreen {
    self.isfull = NO;
}
//将要离开页面时 移除
-(void)viewWillDisappear:(BOOL)animated
{
    if (!self.isfull) {
        if (self.movieView.view) {
            [[NSNotificationCenter defaultCenter]postNotificationName:@"remove" object:nil];
        }
    }
}
@end
